<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Metadata
{
    private $_ci;
    var $metadata = array();

    public function __construct()
    {
        $this->_ci = & get_instance();
        @include(APPPATH . 'config/metadataDB.php');
        if (isset($metadata))
            $this->metadata = $metadata;
    }

    public function get_value($key, $group)
    {
        if (isset($this->metadata[$group][$key])) {
            return $this->metadata[$group][$key];
        }
        return false;
    }

    public function get_metadata($key, $group, $pass_values = array(), $default = false, $page = false)
    {
        $return = $this->get_value($key, $group);
        if ($return) {
            if (!empty($pass_values)) {
                foreach ($pass_values as $f => $r) {
                    $return = preg_replace('/' . $f . '/im', $r, $return);
                }
            } else {
                $return = $this->metadata[$group][$key];
            }
        } else {
            $return = ($default ? $default : '');
        }
        return $this->append_site_name($return, $page);
    }

    public function apply_page_number($pageno)
    {
        if (!$pageno)
            return;
        $page_template = $this->get_value('_global_page_no', 'others');
        return preg_replace('/{page}/im', $pageno, $page_template);
    }

    public function append_site_name($string, $pageno)
    {
        if (!$string)
            return false;
        return $this->remove_Empty_space($string . $this->apply_page_number($pageno) . ' | ' . $this->_ci->config->item('site_name'));
    }

    public function remove_Empty_space($str)
    {
        return trim(preg_replace('/\s+/im', ' ', $str));
    }
}